package com.nowcoder.community.controller;

import com.nowcoder.community.entity.Event;
import com.nowcoder.community.event.EventProducer;
import com.nowcoder.community.util.CommunityConstant;
import com.nowcoder.community.util.CommunityUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName ShareController
 * @Description
 * @Author hhwu
 * @Date 2022/6/1 22:02
 * Version 1.0
 **/

@Controller
public class ShareController implements CommunityConstant {
    /**
     * @Author hhwu
     * @Description //TODO 生成和查看长图
     * @Date 22:03 2022/6/1
     **/

    private static final Logger logger = LoggerFactory.getLogger(ShareController.class);

    @Autowired
    private EventProducer eventProducer;

    @Value("${community.path.domain}")
    private String domain;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Value("${wk.image.storage}")
    private String wkImageStorage;

    @RequestMapping(path = "/share", method = RequestMethod.GET)
    @ResponseBody// 异步请求这里返回JSON
    public String share(String htmlUrl) {
        /**
         * @Author hhwu
         * @Description //TODO 使用消息队列进行异步生成长图，因为时间较长
         * @Date 22:04 2022/6/1
         * @Param [htmlUrl]
         * @return java.lang.String
         **/
        // 随机文件名
        String fileName = CommunityUtil.generateUUID();

        // 触发事件，消息队列异步生成长图
        Event event = new Event()
                .setTopic(TOPIC_SHARE)
                .setData("htmlUrl", htmlUrl)
                .setData("fileName", fileName)
                .setData("suffix", ".png");
        eventProducer.fireEvent(event);

        // 生成长图后，返回指定访问路径
        Map<String, Object> map = new HashMap<>();
        map.put("shareUrl", domain + contextPath + "/share/image/" + fileName);// 生成的长图的路径，也就是下面的方法controller

        return CommunityUtil.getJSONString(0, null, map);
    }

    @RequestMapping(path = "/share/image/{fileName}", method = RequestMethod.GET)
    public void getShareImage(@PathVariable("fileName") String fileName, HttpServletResponse response) {
        /**
         * @Author hhwu
         * @Description //TODO 用户获取长图，给浏览器返回图片
         * @Date 22:04 2022/6/1
         * @Param [fileName, response]
         * @return void
         **/
        if (StringUtils.isBlank(fileName)) {
            throw new IllegalArgumentException("文件名不能为空!");
        }

        response.setContentType("image/png");// 声明输出的是图片，并且是png格式的
        File file = new File(wkImageStorage + "/" + fileName + ".png");// 服务器上图片的地址，而非url
        try {
//            本地图片的读取操作
            OutputStream os = response.getOutputStream();
            FileInputStream fis = new FileInputStream(file);
            byte[] buffer = new byte[1024];
            int b = 0;
            while ((b = fis.read(buffer)) != -1) {
                os.write(buffer, 0, b);
            }
        } catch (IOException e) {
            logger.error("获取长图失败: " + e.getMessage());
        }
    }

}
